import rsaUtil from '@/utils/rsaUtil.js'
import aesUtil from '@/utils/aesUtil.js'
import {exchangeKey} from '@/api/home.js'

export function keyinit(){
    // 首页生成前端rsa密钥对
    var keyPair = rsaUtil.genKeyPair();
    window.rsaPublicKey = keyPair.publicKey;
    window.rsaPrivateKey = keyPair.privateKey;
    exchangeKey().then(res=>{
        window.rsaPublicKeyBe = res.data.data
    })
}

export function decryptResp(res){
    // 解密响应
    var aesCipherData = res.data;
    var rsaCipherAesKey = res.aesKey;
    var aesKey = rsaUtil.decrypt(rsaCipherAesKey, rsaPrivateKey);
    var data = aesUtil.decrypt(aesCipherData, aesKey);
    return data;
}

export function encryptReq(data){
    // 加密请求
    var aesKey = aesUtil.genKey();
    var data = {
        data: aesUtil.encrypt(data,aesKey),
        aesKey: rsaUtil.encrypt(aesKey,rsaPublicKeyBe),
        publicKey: rsaPublicKey
    };
    return data;
}